<?php

namespace app\common\controller;

use think\Controller;
use think\Db;
use think\exception\HttpResponseException;
use think\Request;
use think\Session;

class Token extends Controller
{
    //返回json数据带状态码
    public function responseJson($data = [],$code = 0)
    {
        $msg =  $GLOBALS['ERR_CODE'][$code] ? $GLOBALS['ERR_CODE'][$code] : '';
        throw new HttpResponseException(json(['code'=>$code,'msg'=> $msg,'data'=>$data]));
    }

    //用户登录时生成token
    public function setToken($account)
    {
        $str = md5(uniqid(md5(microtime(true))),true);//生成一个不会重复的token值
        $str = sha1($str);//加密
        $token =  [
            'token' => $str,
            'account' => $account,
        ];
        $this->deposit($token);
        return $str;

    }

    //把用户登录时生成的token验证码存入数据库
    public function deposit($token)
    {
        //判断生成token是否成功
        if (empty($token['token'])){
            $this->responseJson([],5001);
        }
        $date = Db::name('admin')->where('account','like','%'.$token['account'].'%')->field('id')->find();
        //判断账号是否存在
        if (empty($date)){
            $this->responseJson([],5002);
        }
        $tmp = Db::name('admin')->where('id',$date['id'])->update(['token' => $token['token']]);
        if (!$tmp){
            $this->responseJson([],1001);
        }
    }
    //验证token
    public function checkToken($token)
    {
        //判断token是否存在
        if (empty($token)){
            $this->responseJson([],5003);
        }
        $tmp = Db::name('admin')->where('token',$token)->find();
        //判断token 是否正确check
        if (empty($tmp)){
            $this->responseJson([],5003);
        }
        return true;
    }
}
